package com.example.travelsn.viewspot;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.example.travelsn.R;
import com.example.travelsn.util.NavigateView;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ViewSpotHome extends AppCompatActivity {
    private ListView listView;
    private Button cateFresh;

    final Context context = this;
    private LocationClient mLocationClient = null;
    private ViewSpotHome.MyLocationListener myListener = new ViewSpotHome.MyLocationListener();
    private PoiSearch cPoiSearch,c2PoiSearch;
    private int pageSearch = 0;
    private List<Map<String, Object>> listItem;
    //定位相关
    private double cLatitude;
    private double cLongtitude;
    private String myAddressStr;
    private String city;
    private boolean isLocationFirst = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view);
        SDKInitializer.initialize(getApplicationContext());
        SDKInitializer.setCoordType(CoordType.BD09LL);
        initView();
        initMyLocation();
        cateFresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                poiSearch(pageSearch);
                //每次刷新查询下一页
                pageSearch++;
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HashMap<String,String> map=(HashMap<String,String>)listView.getItemAtPosition(position);
                String detailUrl = map.get("detail");
                if(detailUrl.equals("") || detailUrl == null){
                    Toast.makeText(ViewSpotHome.this, "没有详情页", Toast.LENGTH_SHORT).show();
                }
                else{
                    Intent intent = new Intent(ViewSpotHome.this,ViewDetail.class);
                    intent.putExtra("url",detailUrl);
                    startActivity(intent);
                }

            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                new AlertDialog.Builder(context).setTitle("去这个地方吗？")
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                HashMap<String,String> map=(HashMap<String,String>)listView.getItemAtPosition(position);
                                SharedPreferences sharedPreferences = getSharedPreferences("navigation",MODE_PRIVATE);
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.clear();
                                editor.putFloat("blatitude",(float) cLatitude);
                                editor.putFloat("blongitude", (float) cLongtitude);
                                editor.putString("end",map.get("name"));
                                editor.putString("city",map.get("city"));
                                editor.commit();
                                Intent intent = new Intent(ViewSpotHome.this, NavigateView.class);
                                startActivity(intent);

                            }
                        })
                        .setNegativeButton("返回", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
                return true;
            }
        });
    }
    private void initView(){
        listView = (ListView)findViewById(R.id.lv_view);
        cateFresh = (Button)findViewById(R.id.viewfresh);
        listItem = new ArrayList<>();
    }
    //定位
    private void initMyLocation() {
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        //每10s刷新一次位置请求
        option.setScanSpan(10000);
        //需要地址具体信息
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }
    private class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location){
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            cLatitude = location.getLatitude();    //获取纬度信息
            cLongtitude = location.getLongitude();    //获取经度信息
            myAddressStr = location.getAddrStr();
            city = location.getCity();
            if(isLocationFirst == true){
                poiSearch(pageSearch);
                pageSearch++;
                isLocationFirst = false;
            }
            float radius = location.getRadius();    //获取定位精度，默认值为0.0f
            String coorType = location.getCoorType();
            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
            int errorCode = location.getLocType();
            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
        }
    }
    //poi
    private void poiSearch(int page){
        cPoiSearch = PoiSearch.newInstance();
        OnGetPoiSearchResultListener listener = new OnGetPoiSearchResultListener() {
            @Override
            public void onGetPoiResult(PoiResult poiResult) {
                if (poiResult == null || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {// 没有找到检索结果
                    Toast.makeText(ViewSpotHome.this, "在附近未找到，换个关键字试试吧！",
                            Toast.LENGTH_SHORT).show();
                    System.out.println(poiResult.getAllAddr());
                    return;
                }
                if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {
                    Toast.makeText(ViewSpotHome.this, "正在检索附近美食",
                            Toast.LENGTH_SHORT).show();
                    int m =poiResult.getTotalPoiNum();
                    System.out.println(m);
                    List<PoiInfo> allPoi = poiResult.getAllPoi();
                    DecimalFormat df=new DecimalFormat("0.00");
                    for (int i = 0; i < allPoi.size(); i++) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("name",allPoi.get(i).getName());//获取的所有poi相关名字
                        if(allPoi.get(i).getPoiDetailInfo().overallRating == 0){
                            map.put("rating","暂无");
                        }else{
                            map.put("rating",allPoi.get(i).getPoiDetailInfo().overallRating);//对应的评分
                        }                        map.put("distance",df.format(allPoi.get(i).getPoiDetailInfo().distance*0.001)+"km ");//对应的城市
                        //System.out.println("环境评分是"+allPoi.get(i).poiDetailInfo.environmentRating);
                        map.put("address",allPoi.get(i).getAddress());//对应的详细地址
                        map.put("location",allPoi.get(i).getLocation());//对应的位置的经纬度
                        if(allPoi.get(i).getDetail() == 1){
                            map.put("detail",allPoi.get(i).getPoiDetailInfo().getDetailUrl());
                        }
                        if(!map.isEmpty() && map !=null){
                            listItem.add(map);
                        }else System.out.println("map为空");
                    }
                    if(listItem!=null && !listItem.isEmpty()){
                        SimpleAdapter adapter = new SimpleAdapter(ViewSpotHome.this
                                , listItem
                                , R.layout.listview_view
                                , new String[]{"name","address","distance","rating"}
                                , new int[]{R.id.view_content,R.id.view_detail_address,R.id.view_other,R.id.view_rating});
                        listView.setAdapter(adapter);
                    }
                }
            }

            @Override
            public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {

            }
            @Override
            public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

            }
            //废弃
            @Override
            public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

            }
        };
        cPoiSearch.setOnGetPoiSearchResultListener(listener);
        /**
         * 以我的位置为中心，在半径5000米以内搜索
         */
        cPoiSearch.searchNearby(new PoiNearbySearchOption()
                .location(new LatLng(cLatitude, cLongtitude))
                .radius(500000)
                .keyword("景点")
                .scope(2)
                .pageNum(page)
                .pageCapacity(20));
        cPoiSearch.destroy();
    }
}
